package com.yx.musicplayer.util;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import com.yx.musicplayer.bean.Album;
import com.yx.musicplayer.bean.Artist;
import com.yx.musicplayer.bean.FolderInfo;
import com.yx.musicplayer.greendao.Song;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;

/**
 * @ClassName 查询歌曲工具类
 * Created by yx on 2017/11/1 0001.
 */

public class QuerySongUtil {

    /**
     * 查询所有歌曲信息
     * @param context
     * @param media
     * @return
     */
    public static Observable<List<Song>> queryAllSong(Context context, String media) {
        String selectionStatement = "is_music=1 AND title != ''";

        final Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{"_id", "title", "artist", "album", "duration", "track", "artist_id", "album_id", MediaStore.Audio.Media.DATA},
                selectionStatement, null, media);

        return Observable.create(new Observable.OnSubscribe<List<Song>>() {
            @Override
            public void call(Subscriber<? super List<Song>> subscriber) {
                List<Song> arrayList = new ArrayList<Song>();
                if ((cursor != null) && (cursor.moveToFirst())) {
                    do {
                        long id = cursor.getLong(0);
                        String title = cursor.getString(1);
                        String artist = cursor.getString(2);
                        String album = cursor.getString(3);
                        int duration = cursor.getInt(4);
                        int trackNumber = cursor.getInt(5);
                        long artistId = cursor.getInt(6);
                        long albumId = cursor.getLong(7);
                        String path = cursor.getString(8);

                        arrayList.add(new Song(id, albumId, artistId, title, artist, album, duration, trackNumber, path));
                    }
                    while (cursor.moveToNext());
                }
                if (cursor != null) {
                    cursor.close();
                }
                subscriber.onNext(arrayList);
                subscriber.onCompleted();
            }
        });
    }


    /**
     * 查询所有艺术家信息
     * @param context
     * @return
     */
    public static Observable<List<Artist>> getAllArtists(Context context) {
        final Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, new String[]{"_id", "artist", "number_of_albums", "number_of_tracks"}, null, null, MediaStore.Audio.Media.ARTIST);
        return Observable.create(new Observable.OnSubscribe<List<Artist>>() {
            @Override
            public void call(Subscriber<? super List<Artist>> subscriber) {
                List<Artist> arrayList = new ArrayList<Artist>();
                if ((cursor != null) && (cursor.moveToFirst())) {
                    do {
                        arrayList.add(new Artist(cursor.getLong(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3)));
                    }
                    while (cursor.moveToNext());
                }
                if (cursor != null) {
                    cursor.close();
                }
                subscriber.onNext(arrayList);
                subscriber.onCompleted();
            }
        });
    }

    /**
     * 查询所有专辑信息
     * @param context
     * @return
     */
    public static Observable<List<Album>> getAllAlbums(Context context) {
        final Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[]{"_id", "album", "artist", "artist_id", "numsongs", "minyear"}, null, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
        return Observable.create(new Observable.OnSubscribe<List<Album>>() {
            @Override
            public void call(Subscriber<? super List<Album>> subscriber) {
                List<Album> arrayList = new ArrayList<>();
                if ((cursor != null) && (cursor.moveToFirst())) {
                    do {
                        arrayList.add(new Album(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getLong(3), cursor.getInt(4), cursor.getInt(5)));
                    }
                    while (cursor.moveToNext());
                }
                if (cursor != null) {
                    cursor.close();
                }
                subscriber.onNext(arrayList);
                subscriber.onCompleted();
            }
        });
    }

    /**
     * 检索包含音频文件的文件夹, 并统计该文件夹下的歌曲数目
     *
     * @return
     */
    public static Observable<List<FolderInfo>> getFoldersWithSong(final Context context) {
        final List<FolderInfo> folderInfos = new ArrayList<FolderInfo>();
        final String num_of_songs = "num_of_songs";
        final String[] projection = new String[]{MediaStore.Files.FileColumns.DATA,
                "count(" + MediaStore.Files.FileColumns.PARENT + ") as " + num_of_songs};

        final String selection = " is_music=1 AND title != '' " + " ) " + " group by ( "
                + MediaStore.Files.FileColumns.PARENT;

        return Observable.create(new Observable.OnSubscribe<List<FolderInfo>>() {
            @Override
            public void call(Subscriber<? super List<FolderInfo>> subscriber) {
                Cursor cursor = context.getContentResolver().query(
                        MediaStore.Files.getContentUri("external"), projection, selection, null, null);

                if (cursor != null) {
                    int index_data = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
                    int index_num_of_songs = cursor.getColumnIndex(num_of_songs);

                    while (cursor.moveToNext()) {

                        // 获取每个目录下的歌曲数量
                        int songCount = cursor.getInt(index_num_of_songs);

                        // 获取文件的路径，如/storage/sdcard0/MIUI/music/Baby.mp3
                        String filepath = cursor.getString(index_data);

                        // 获取文件所属文件夹的路径，如/storage/sdcard0/MIUI/music
                        String folderpath = filepath.substring(0, filepath.lastIndexOf(File.separator));

                        // 获取文件所属文件夹的名称，如music
                        String foldername = folderpath.substring(folderpath.lastIndexOf(File.separator) + 1);

                        folderInfos.add(new FolderInfo(foldername, folderpath, songCount));
                    }
                }

                if (cursor != null) {
                    cursor.close();
                }
                subscriber.onNext(folderInfos);
            }
        });
    }



}
